/*
 * @Descripttion: 组件业务名
 * @version:
 * @Author: lhl
 * @Date: 2024-10-25 11:06:36
 * @LastEditors: lhl
 * @LastEditTime: 2024-10-25 11:20:22
 */
import { useState, useEffect } from 'react';
import { useAuth } from './useAuth';
import { MenuItem } from '@/router/type';
import { menuApi } from '@/api/system'; // 假设有这个 API 函数来获取菜单列表

export const useRoutes = () => {
  const [routes, setRoutes] = useState<MenuItem[]>([]);
  const { userInfo } = useAuth();

  useEffect(() => {
    const fetchRoutes = async () => {
      if (userInfo) {
        try {
          const { data } = await menuApi();
          const filteredRoutes = filterRoutesByPermission(data, userInfo.perms);
          setRoutes(filteredRoutes);
        } catch (error) {
          console.error('获取菜单列表失败:', error);
        }
      }
    };

    fetchRoutes();
  }, [userInfo]);

  return routes;
};

const filterRoutesByPermission = (routes: MenuItem[], permissions: string[]): MenuItem[] => {
  return routes.filter((route) => {
    if (route.meta?.permissions && !route.meta.permissions.some((perm) => permissions.includes(perm))) {
      return false;
    }
    if (route.children) {
      route.children = filterRoutesByPermission(route.children, permissions);
    }
    return true;
  });
};
